package com.leave.web.servlet;

import com.google.gson.Gson;
import com.leave.context.AppContext;
import com.leave.entity.Classes;
import com.leave.service.ClassesService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "classesServlet",  urlPatterns = {"/classes"})
public class ClassesServlet extends HttpServlet {

    private final static String CLASSES_LIST = "/WEB-INF/views/instructor/instructor_classes.jsp";

    private final Logger logger = LoggerFactory.getLogger(LeaveServlet.class);

    private ClassesService classesService;


    @Override
    public void init() throws ServletException {
        super.init();
        //从IoC容器获取实例化bean组件
        classesService = AppContext.getBean(ClassesService.class);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        HttpSession session = req.getSession();
        logger.info("request process starting" + action);
        String classID = req.getParameter("classID");
        String className = req.getParameter("className");
        String depID = req.getParameter("depID");
        String major = req.getParameter("major");
        String grade = req.getParameter("grade");
        String keyword = req.getParameter("keyword");
        resp.setContentType("text/plain");
//        // 设置响应类型为 JSON
//        resp.setContentType("application/json");
//        resp.setCharacterEncoding("UTF-8");
//
//        // 创建一个 JSON 响应对象
//        Map<String, String> responseMap = new HashMap<>();

        try {
            //2:调用userService完成处理,此处switch语句的语法要求jdk1.8以上。
            switch (action) {
                case "list":
                    List<Classes> classesList = classesService.classesList(null);
                    session.setAttribute("list", classesList);
                    req.getRequestDispatcher(CLASSES_LIST).forward(req, resp);
                    break;
                case "seek":
                    try {
                        List<Map<String, Object>> claSeekList = classesService.seek(keyword);
                        // 将查询结果传递给前端进行展示
                        session.setAttribute("list", claSeekList);
                        req.getRequestDispatcher(CLASSES_LIST).forward(req, resp);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }

                    break;
                case "delete":
                    boolean successD = classesService.deleteClass(classID);
                    if (successD) {
                        // 表单提交成功
                        req.setAttribute("successMessage", "班级信息删除成功！");
                    } else {
                        // 数据写入失败
                        req.setAttribute("errorMessage", "班级信息删除失败，请重试！");
                    }
                    req.getRequestDispatcher("classes?action=list").forward(req, resp);
                    break;
                case "add":
                    Classes classes = new Classes();
                    //接收表单(Form)参数,并转换为实体对象的属性值
                    resolveRequestParameter(req,classes);
//                    System.out.println(classes+"classes");
                    //调用service组件完成数据写入
                    boolean success = classesService.addClass(classes);
                    if (success) {
                        // 表单提交成功
                        req.setAttribute("successMessage", "班级添加成功！");
                    } else {
                        // 数据写入失败
                        req.setAttribute("errorMessage", "班级添加失败，请重试！");
                    }
                    req.getRequestDispatcher("classes?action=list").forward(req, resp);
//                    resp.getWriter().write(success ? "添加成功" : "添加失败");
                    break;
                case "edit":
                    Classes classes_01 = new Classes();
                    resolveRequestParameter(req,classes_01);
//                    System.out.println("daozheli");
                    boolean successE = classesService.editClass(classes_01);
                    if (successE) {
                        // 表单提交成功
                        req.setAttribute("successMessage", "班级信息修改成功！");
                    } else {
                        // 数据写入失败
                        req.setAttribute("errorMessage", "班级信息修改失败，请重试！");
                    }
                    req.getRequestDispatcher("classes?action=list").forward(req, resp);
                    break;
            }

        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void resolveRequestParameter(HttpServletRequest req, Object bean) {
        Map<String, String[]> reqParameterMap = req.getParameterMap();
        System.out.println("reqParameterMap+" + reqParameterMap);
        Map<String, String[]> propertiesMap = new HashMap<String, String[]>();
        try {
            for (Map.Entry<String, String[]> entry : reqParameterMap.entrySet()) {
                String name = entry.getKey();
                String[] values = entry.getValue();
                // 判断 request 参数是否对应 JavaBean 对象的属性
                Class<?> propertyType = PropertyUtils.getPropertyType(bean, name);
                if (propertyType != null) {
                    propertiesMap.put(name, values);
                }
            }
            // 转换为 POJO 对象 bean 的属性值
            BeanUtils.populate(bean, propertiesMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("The property name could not be found", e);
        }
    }
}
